package org.light.verb;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Field;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.Type;
import org.light.domain.Var;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.generator.NamedStatementGenerator;
import org.light.generator.NamedStatementListGenerator;
import org.light.utils.DomainTokenUtil;
import org.light.utils.InterVarUtil;
import org.light.utils.MybatisSqlReflector;
import org.light.utils.PgsqlReflector;
import org.light.utils.StringUtil;
import org.light.utils.TableStringUtil;
import org.light.utils.WriteableUtil;

public class SearchByName extends Verb implements EasyUIPositions {
	protected Set<Field> deniedFields = new TreeSet<>();

	@Override
	public Method generateDaoImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("Search" + StringUtil.capFirst(this.domain.getPlural()) + "By"
					+ this.domain.getDomainName().getCapFirstFieldName());
			method.setNoContainer(false);
			method.addSignature(new Signature(1, "db","*sql.DB"));
			method.addSignature(new Signature(2, this.domain.getDomainName().getLowerFirstFieldName(),"string"));
			method.setReturnType(new Type("[] "+this.domain.getDomainSuffix()+ "."+this.domain.getCapFirstDomainNameWithSuffix()));

			List<Writeable> sList = new ArrayList<Writeable>();
			
			if (StringUtil.isBlank(this.getDbType())||this.getDbType().equalsIgnoreCase("MariaDB")||this.getDbType().equalsIgnoreCase("MySQL")) {
				sList.add(new Statement(3000L,1,"query := \"select " + DomainTokenUtil.generateTableCommaFieldsWithDeniedFields(domain,this.deniedFields) + " from " + domain.getDbPrefix() + TableStringUtil.domainNametoTableName(domain)+" where "+DomainTokenUtil.changeDomainFieldtoTableColum(this.domain.getDomainName().getLowerFirstFieldName())+" like '%?%'\""));
			}else if (this.getDbType().equalsIgnoreCase("PostgreSQL")||this.getDbType().equalsIgnoreCase("pgsql")) {
				sList.add(new Statement(3000L,1,"query := \"select " + DomainTokenUtil.generateTableCommaFieldsWithDeniedFields(domain,this.deniedFields) + " from " + domain.getDbPrefix() + TableStringUtil.domainNametoTableName(domain)+" where "+DomainTokenUtil.changeDomainFieldtoTableColum(this.domain.getDomainName().getLowerFirstFieldName())+" like '%$1%'\""));
			}
			
			sList.add(new Statement(4000L,0,""));
			long serial = 5000L;
			sList.add(new Statement(serial+3000L,0,""));
			sList.add(new Statement(serial+6000L,1,"stmt, err := db.Prepare(query)"));
			sList.add(new Statement(serial+7000L,1,"if err != nil {"));
			sList.add(new Statement(serial+8000L,2,"panic(err)"));
			sList.add(new Statement(serial+9000L,1,"}"));
			sList.add(new Statement(serial+10000L,0,""));
			sList.add(new Statement(serial+11000L,1,"rows, err := stmt.Query("+this.domain.getDomainName().getLowerFirstFieldName()+")"));
			sList.add(new Statement(serial+12000L,1,"if err != nil {"));
			sList.add(new Statement(serial+13000L,2,"panic(err)"));
			sList.add(new Statement(serial+14000L,1,"}"));
			
			sList.add(new Statement(serial+15000L,1,"var "+this.domain.getLowerFirstPlural()+" [] "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
			sList.add(new Statement(serial+16000L,0,""));
			sList.add(new Statement(serial+17000L,1,"for rows.Next() {"));
			serial += 18000L;
			StringBuilder sb = new StringBuilder();
			for (Field f:this.domain.getFields()) {
				sList.add(new Statement(serial,2,"var "+f.getLowerFirstFieldName()+" "+ f.getFieldTypeWithParseImage()));
				sb.append("&").append(f.getLowerFirstFieldName()).append(",");
				serial += 1000L;
			}
			String fieldsQuery = sb.toString();
			if (fieldsQuery.endsWith(",")) fieldsQuery = fieldsQuery.substring(0,fieldsQuery.length()-1);

			sList.add(new Statement(serial,0,""));
			sList.add(new Statement(serial+1000L,2,"err := rows.Scan("+fieldsQuery+")"));
			sList.add(new Statement(serial+2000L,2,"if err != nil {"));
			sList.add(new Statement(serial+3000L,3,"panic(err)"));
			sList.add(new Statement(serial+4000L,2,"}"));
			sList.add(new Statement(serial+5000L,2,"var "+this.domain.getLowerFirstDomainName()+" "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
			serial += 6000L;
			for (Field f:this.domain.getFields()) {
				sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"("+f.getLowerFirstFieldName()+")"));
				serial += 1000L;
			}
			sList.add(new Statement(serial,2,""+this.domain.getLowerFirstPlural()+" = append("+this.domain.getLowerFirstPlural()+", "+this.domain.getLowerFirstDomainName()+")"));
			sList.add(new Statement(serial+1000L,1,"}"));
			sList.add(new Statement(serial+2000L,1,"return "+this.domain.getLowerFirstPlural()+""));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}
	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("search" + this.domain.getPlural() + "By"
					+ StringUtil.capFirst(this.domain.getDomainName().getFieldName()));
			method.setReturnType(new Type("List", this.domain, this.domain.getPackageToken()));
			method.addSignature(new Signature(1, this.domain.getDomainName().getFieldName(), new Type("String")));

			return method;
		}
	}
	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("Search" + this.domain.getPlural() + "By"
					+ StringUtil.capFirst(this.domain.getDomainName().getFieldName()));
			method.setReturnType(new Type("List", this.domain, this.domain.getPackageToken()));
			method.addSignature(new Signature(1, this.domain.getDomainName().getFieldName(), new Type("String")));

			return method;
		}
	}
	@Override
	public Method generateServiceImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName(""
					+ "Search" + this.domain.getPlural() + "By"
					+ StringUtil.capFirst(this.domain.getDomainName().getFieldName()));
			method.setReturnType(new Type("[] "+this.domain.getDomainSuffix()+"."+this.domain.getType()));
			method.addSignature(new Signature(1, this.domain.getDomainName().getFieldName(), new Type("string")));
			
			Method daomethod = this.generateDaoMethodDefinition();

			List<Writeable> list = new ArrayList<Writeable>();
			list.add(new Statement(1000L,1,"db := database.DB"));
			list.add(new Statement(3000L, 1, "return "+this.domain.getDaoimplSuffix()+".Search" + this.domain.getCapFirstPlural() + "By"+this.domain.getDomainName().getCapFirstFieldName()+"(db,"
					+ this.domain.getDomainName().getLowerFirstFieldName() + ")"));
			method.setMethodStatementList(WriteableUtil.merge(list));

			return method;
		}
	}
	public SearchByName() {
		super();
		this.dbType = "MariaDB";
		this.setLabel("按名字搜索");
	}

	public SearchByName(Domain domain)  throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = "MariaDB";
		this.denied = domain.isVerbDenied("SearchByName");
		this.setVerbName("Search" + this.domain.getPlural() + "By"
				+ StringUtil.capFirst(this.domain.getDomainName().getFieldName()));
		this.setLabel("按名字搜索");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("SearchByName");
	}
	
	public SearchByName(Domain domain, String dbType)  throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = dbType;
		this.denied = domain.isVerbDenied("SearchByName");
		this.setVerbName("Search" + this.domain.getPlural() + "By"
				+ StringUtil.capFirst(this.domain.getDomainName().getFieldName()));
		this.setLabel("按名字搜索");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("SearchByName");
	}

	@Override
	public Method generateControllerMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("Search" + this.domain.getPlural() + "By"
					+ StringUtil.capFirst(this.domain.getDomainName().getFieldName()));
			method.addSignature(new Signature(1,"c","*gin.Context"));

			List<Writeable> wlist = new ArrayList<Writeable>();
			Var service = new Var("service",
					new Type(this.domain.getStandardName() + "Service", this.domain.getPackageToken()));
			Var vlist = new Var(this.domain.getLowerFirstDomainName() + "List",
					new Type("List", this.domain, this.domain.getPackageToken()));
			Method serviceMethod = this.generateServiceMethodDefinition();
			Var resultMap = new Var("result", new Type("TreeMap<String,Object>", "java.util"));
			wlist.add(NamedStatementGenerator.getJsonResultMap(1000L, 2, resultMap));
			wlist.add(new Statement(2000L, 2,
					vlist.getVarType() + " " + vlist.getVarName() + " = " + service.getVarName() + "."
							+ serviceMethod.getStandardName() + "("
							+ this.domain.getDomainName().getLowerFirstFieldName() + ");"));
			wlist.add(NamedStatementListGenerator.getPutJsonResultMapWithSuccessAndDomainList(3000L, 2, resultMap,
					vlist));
			wlist.add(new Statement(4000L, 2, "return " + resultMap.getVarName() + ";"));
			method.setMethodStatementList(WriteableUtil.merge(wlist));

			return method;
		}
	}
	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		return null;
	}
	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			return null;
		}
	}
}
